package cn.dansj.handler.interfaces;

import cn.dansj.annotation.MarkAsApi;
import cn.dansj.annotation.InterfaceParam;
import cn.dansj.bean.CurrentThreadLocalUserInfo;
import cn.dansj.common.utils.json.DictMap;
import cn.dansj.entity.User;
import cn.dansj.common.utils.enums.ResponseCode;
import cn.dansj.exception.InterfaceResponseException;
import cn.dansj.common.request.RestTemplateUtils;
import cn.dansj.common.utils.transfer.Verification;
import cn.dansj.handler.InterfaceHandler;
import cn.dansj.utils.interfaces.InterfaceUtils;

import java.util.Map;

@SuppressWarnings("all")
@MarkAsApi
public class BindWxOpenid extends InterfaceHandler {
    @InterfaceParam(value = "code", require = true, comment = "微信用户code")
    @Override
    public Object execute(Map<String, Object> paramsMap) {
        try {
            Object code = paramsMap.get("code");
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx21cc4de5168e41c4&secret=078163ccf888c6800ebdf2705a82d564&js_code=" + code + "&grant_type=authorization_code";
            String openid = DictMap.parseObject(RestTemplateUtils.defaultInstance().get(url, String.class)).getString("openid");
            User user = DictMap.parseObject(jdbcTemplate.queryForMap("select * from x_user_info where open_id=?", openid), User.class);

            if (user != null && Verification.checkNotNull(user.getOpenId())) {
                throw new InterfaceResponseException(ResponseCode.AuthenticationFailed.getStatusCode(), "当前微信已绑定用户");
            } else {
                String userId = CurrentThreadLocalUserInfo.getCurrentThreadLocalUserInfo().getCacheToken().getSequence();
                final int update = jdbcTemplate.update("update x_user_info set open_id=? where sequence=?", openid, userId);
                return update == 1 ? "绑定成功" : "绑定失败";
            }
        } catch (InterfaceResponseException interfaceResponseException) {
            throw interfaceResponseException;
        } catch (Exception exception) {
            InterfaceUtils.logger.error("error:", exception);
            throw new InterfaceResponseException(ResponseCode.AuthenticationFailed);
        }
    }
}